/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package org.apache.hop.pipeline.transforms.agentscript;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import org.apache.hop.core.Const;
import org.apache.hop.core.exception.HopTransformException;
import org.apache.hop.core.row.IRowMeta;
import org.apache.hop.core.util.StringUtil;
import org.apache.hop.core.variables.IVariables;
import org.apache.hop.pipeline.PipelineMeta;
import org.apache.hop.pipeline.transform.BaseTransformMeta;
import org.apache.hop.pipeline.transform.ITransformDialog;
import org.apache.hop.ui.core.PropsUi;
import org.apache.hop.ui.core.dialog.BaseDialog;
import org.apache.hop.ui.pipeline.transform.BaseTransformDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;

/** 对名称有要,必须是metadata的类名称+Dialog组成窗口对象 */
public class AgentScriptMetaDataDialog extends BaseTransformDialog implements ITransformDialog {
  private static final Class<?> PKG = AgentScriptMetaDataDialog.class; // for Translator
  private final AgentScriptMetaData metaData;

  private Browser wBrowser;

  public AgentScriptMetaDataDialog(
      Shell parent, IVariables variables, Object in, PipelineMeta tr, String sname) {
    super(parent, variables, (BaseTransformMeta) in, tr, sname);
    this.metaData = (AgentScriptMetaData) in;

    // 获取上 一个 输入变量,把变量名称也更新到表里面,前一个节点输入字段
    String prefields = "";
    IRowMeta preMeta;
    try {
      preMeta = pipelineMeta.getPrevTransformFields(variables, transformName);
      if (preMeta != null) {
        prefields = Arrays.toString(preMeta.getFieldNames());
        System.out.println("[cancel]prevMetaFields=" + prefields);
      }
    } catch (HopTransformException ignore) {
      // Do nothing
    }

    // 如果pipe里面没有配置值,就在表里面新建记录.如果配置了值,更新表里面值为pipe文件里面值,以pipe的为准
    String xml = this.metaData.getXmlData(transformName);
    System.out.println("[construct]read-xml=" + xml);
    String id = this.metaData.getId();

    String param = String.format("\"xmlcnt\":\"%s\",\"prefields\":\"%s\"", xml, prefields);
    // 如果是新增加的节点,直接保存到数据库
    if (StringUtil.isEmpty(id)) {
      id = Const.odataUpsert("", "AidbTransformPropertyTabs", param);
      if (StringUtil.isEmpty(id)) {
        return;
      }
      System.out.println("[construct]read-id=" + id);
      this.metaData.setId(id);
      xml = this.metaData.getXmlData(transformName);
      System.out.println("[construct]read-xml=" + xml);
      param = String.format("\"xmlcnt\":\"%s\",\"prefields\":\"%s\"", xml, prefields);
      Const.odataUpsert(id, "AidbTransformPropertyTabs", param);
      return;
    }
    Const.odataUpsert(id, "AidbTransformPropertyTabs", param);
  }

  public String open() {
    Shell parent = getParent();
    shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.MIN | SWT.MAX | SWT.RESIZE);
    shell.setMinimumSize(400, 200);
    PropsUi.setLook(shell);
    shell.setLayout(new FormLayout());
    shell.setText("设置属性");
    // 计算屏幕尺寸并居中显示
    int screenWidth = parent.getBounds().width;
    int screenHeight = parent.getBounds().height;
    shell.setLocation(
        (screenWidth - shell.getBounds().width) / 2, (screenHeight - shell.getBounds().height) / 2);

    wBrowser = new Browser(shell, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
    FormData fdBrowser = new FormData();
    fdBrowser.left = new FormAttachment(0, 0);
    fdBrowser.top = new FormAttachment(0, 0);
    fdBrowser.right = new FormAttachment(100, 0);
    fdBrowser.bottom = new FormAttachment(100, 0);
    wBrowser.setLayoutData(fdBrowser);

    // JavaScriptExecutor executor = RWT.getClient().getService(JavaScriptExecutor.class);
    // executor.execute("alert");
    System.out.println("[open]this.metaData.getUid= " + this.metaData.getId());
    wBrowser.setUrl(
        "./webpluginsdialog/AgentScript.html?id="
            + this.metaData.getId()
            + "&tm="
            + System.currentTimeMillis());

    shell.open();
    BaseDialog.defaultShellHandling(shell, c -> ok(), c -> cancel());
    return transformName;
  }

  private void cancel() {
    // 从数据库读取内容,点击保存按钮,就可以把内容保存到hpl文件
    // this.metaData.setInputMessage("save-input");
    // this.metaData.setOutputMessage("save-output");
    try {
      // 修改系统的修改的状态
      this.metaData.setChanged(true);
      String id = this.metaData.getId();
      System.out.println("[cancel] id=" + id);
      String filter = URLEncoder.encode("id eq " + id, StandardCharsets.UTF_8).replace("+", "%20");
      String select = URLEncoder.encode("xmlcnt", StandardCharsets.UTF_8).replace("+", "%20");
      String url = "AidbTransformPropertyTabs?$filter=" + filter + "&$select=" + select;
      String xml = Const.odataRead(url);
      if (StringUtil.isEmpty(xml)) {
        MessageBox box = new MessageBox(shell);
        box.setMessage("保存失败");
        box.open();
      }
      transformName = this.metaData.setXmlData(xml);
      System.out.println("[cancel]save-xml=" + xml);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
    dispose();
  }

  private void ok() {
    System.out.println("AgentScriptMetaDataDialog-ok");
    // getInfo(input);
    dispose();
  }
}
